﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WINBASE.Utils;
using WINBASE.Utils.NETHelper;
using WINBASE.Utils.DTHelper;
using WINBASE.Controls;
using System.Reflection;

namespace WINBASE
{
    public partial class WLCFrmSelectList : Form
    {
        public BindingList<KeyValuePair<string, string>> Column1;

        bool IsSystemMode = false;
        bool IsDataGridFormatted;

        #region Event

        public WLCFrmSelectList()
        {
            InitializeComponent();
            InitializeUI();
        }

        private void DataGrid_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Enter | Keys.Return:
                    DataGrid_CellDoubleClick(null, null);
                    e.SuppressKeyPress = true;
                    break;

                default: break;
            }
        }

        private void DataGrid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (DataGrid.DataSource != null && DataGrid.SelectedRows.Count > 0)
            {
                this.DialogResult = DialogResult.OK;
            }
        }

        private void DataGrid_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            cboColumn1.SelectedIndex = this.DataGrid.Columns[e.ColumnIndex].DisplayIndex;
        }

        private void btnChar1_Click(object sender, EventArgs e)
        {
            txtSearch1.Text = txtSearch1.Text.Trim() + "%";
        }

        private void txtSearch1_TextChanged(object sender, EventArgs e)
        {
            if (!IsSystemMode)
            {
                String TextFilter = "";
                if (cboColumn1.SelectedIndex > -1 && txtSearch1.Text.Trim() != "")
                {
                    TextFilter = (QueryFilter.Length <= 0 ? "" : " AND ") + '[' + cboColumn1.Text + ']' + " LIKE('" + txtSearch1.Text.Trim() + "%')";
                }
                this.DataGrid.Filter = this.QueryFilter + TextFilter;
                this.DataGrid.RefreshData();
            }
        }

        private void cboColumn1_TextChanged(object sender, EventArgs e)
        {
            txtSearch1.Focus();
            txtSearch1_TextChanged(null, null);
        }

        private void tspControl_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            ToolStripItem ctrl = ((ToolStripItem)e.ClickedItem);
            switch (ctrl.Name)
            {
                case "btnClear1":
                    txtSearch1.Text = "";
                    txtSearch1.Focus();
                    break;
                case "btnRefresh":
                    this.DataGrid.Refresh();
                    txtSearch1.Focus();
                    break;
                default: break;
            }
        }

        private void btnDetail_Click(object sender, EventArgs e)
        {
            this.Hide();
            _DetailForm.InitializeBaseData();
            DataRowView drCurrent = (DataRowView)((BindingSource)(this.DataGrid.DataSource)).Current;
            _DetailForm.InitializeData(drCurrent);

            _DetailForm.DockHandler.DockPanel = ApplicationObject.FrmMain.dpnlMain;
            _DetailForm.DockHandler.DockAreas = WeifenLuo.WinFormsUI.Docking.DockAreas.Document;
            _DetailForm.Activate();
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
        }

        private void WLCFrmSelectList_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Escape:
                    this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
                    break;
                default: break;
            }
        }

        private void DataGrid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            if (this.IsDataGridFormatted) return;
            InitColumn();
            this.IsDataGridFormatted = true;
        }

        private void WLCFrmSelectList_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.DataGrid.SaveColumnOrder();
        }

        #endregion

        #region Method

        public void InitializeUI()
        {
            IsSystemMode = true;
            if ((this.ViewName ?? "") != "")
            {
                this.DataGrid.Name = "dgv" + this.ViewName.Right(5);
            }
            this.DataGrid.Name = "dgv" + this.Name.Right(5);
            this.DataGrid.CellDoubleClick += DataGrid_CellDoubleClick;
            this.DataGrid.ColumnHeaderMouseClick += DataGrid_ColumnHeaderMouseClick;
            this.DataGrid.KeyDown += DataGrid_KeyDown;
        }

        public void InitializeData()
        {
            Cursor.Current = Cursors.WaitCursor;
            if (this.InvokeRequired)
            {
                this.Invoke((MethodInvoker)delegate
                {
                    InitializeData();
                    return;
                });
            }
            else
            {
                txtSearch1.Text = "";
                btnDetail.Visible = (DetailForm != null);

                if ((this.ViewName ?? "") != "")
                {
                    this.DataGrid.Name = "dgv" + this.ViewName.Right(5);
                    this.DataGrid.Filter = this.QueryFilter;
                    this.DataGrid.ViewName = this.ViewName;
                    this.DataGrid.InitializeData();
                }
                Cursor.Current = Cursors.Default;
                return;
            }
        }

        public void InitializeData(DataTable Dt)
        {
            Cursor.Current = Cursors.WaitCursor;
            if ((this.InvokeRequired))
            {
                this.Invoke((MethodInvoker)delegate
                {
                    InitializeData(Dt);
                    return;
                });
            }
            else
            {
                this.DataGrid.DataPaginated = false;
                this.DataGrid.DataSource = Dt;
                Cursor.Current = Cursors.Default;
                return;
            }
        }

        public void InitColumn()
        {
            Column1 = new BindingList<KeyValuePair<string, string>>();
            foreach (DataGridViewColumn dgvCol in this.DataGrid.Columns)
            {
                string key = dgvCol.DataPropertyName;
                string value = dgvCol.HeaderText;
                Column1.Add(new KeyValuePair<string, string>(key, value));
            }

            cboColumn1.DataSource = Column1;
            cboColumn1.ValueMember = "Key";
            cboColumn1.DisplayMember = "Value";

            this.ResetComboIndex();
        }

        public void ResetComboIndex()
        {
            base.Refresh();
            if (this.DataGrid.SortedColumn != null && this.DataGrid.SortedColumn.Visible == true)
                cboColumn1.SelectedIndex = this.DataGrid.SortedColumn.DisplayIndex;
            else cboColumn1.SelectedIndex = cboColumn1.Items.Count > 0 ? 0 : -1;
        }

        #endregion

        #region Property

        private WLCDetailForm _DetailForm;
        public WLCDetailForm DetailForm
        {
            get { return _DetailForm; }
            set { _DetailForm = value; }
        }

        private string _ViewName;
        public string ViewName
        {
            get { return _ViewName; }
            set 
            { 
                _ViewName = value;
            }
        }

        private string strQf = "";
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public string QueryFilter
        {
            get { return strQf; }
            set { strQf = value; }
        }

        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public DataRow SelectedRow
        {
            get
            {
                if (this.DataGrid.SelectedRows.Count > 0)
                {
                    DataRowView currentDataRowView = (DataRowView)this.DataGrid.CurrentRow.DataBoundItem;
                    try
                    {
                        return currentDataRowView.Row;
                    }
                    catch (Exception ex)
                    {
                        Utils.DBHelper.QueryHelper.ShowMsgException(ex);
                        return null;
                    }
                }
                else return null;
            }
        }

        #endregion
    }
}